﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomsSystem.BLL;
using System.Data;
using CustomsSystem.Model;
using Maticsoft.Common;

namespace WEB.workflow
{
    public partial class workflowSettingView : System.Web.UI.Page
    {
        public static DataTable dt;
        public WorkflowManage bll = new WorkflowManage();
        public static string curWFTYPEID;
        public int curMasterState;
        bool isBeginUsed;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.ClientScript.IsClientScriptBlockRegistered("deleteConfirmBlock"))
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(string), "deleteConfirmBlock", "function deleteConfirm(){confirm( 确认要删除? );}", true);
            }


            if (!IsPostBack)
            {
                BindFlowInfo(ddlSelect);
                
                //检查状态
                adDLLStates();

                
                Info_workflowMaster master = getMasterState(int.Parse(ddlSelect.SelectedValue));
                int state = 0;
                string mName = "";
                if (master != null)
                {
                    mName = master.WKTypeName;
                    state = master.States;
                }
                ddlStates.SelectedIndex  = ddlStates.Items.IndexOf(ddlStates.Items.FindByValue(state.ToString()));
                tbMasterName.Text = mName;
                curWFTYPEID = ddlSelect.SelectedValue.ToString();
                if (curWFTYPEID == "") curWFTYPEID = "-1";
                checkDDLCanUse(ddlStates);

                gvBind();
            }
        }

        private void gvBind()
        {
            curWFTYPEID = ddlSelect.SelectedValue.ToString();
            if (curWFTYPEID == "") curWFTYPEID = "-1";
            dt = bll.GetList(" infoWKTypeID =" + curWFTYPEID).Tables[0];
            if (dt.Rows.Count == 0) panelState.Visible = false;
            else panelState.Visible = true;
            gvWorkflowview.DataSource = dt;
            gvWorkflowview.DataBind();
        }

        protected void ddlSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            adDLLStates();
            curWFTYPEID = ddlSelect.SelectedValue;
            if (curWFTYPEID == "") curWFTYPEID = "-1"; 
            Info_workflowMaster master = getMasterState(int.Parse(curWFTYPEID));
            int state = 0;
            string mName = "";
            if (master != null) state = master.States;

            ddlStates.SelectedIndex = ddlStates.Items.IndexOf(ddlStates.Items.FindByValue(state.ToString()));
            if (master != null) mName = master.WKTypeName;
            tbMasterName.Text = mName;
            //curMasterState = master.States;
            
            checkDDLCanUse(ddlStates);
            gvBind();
            
        }

        protected void ddlSelectState_SelectedIndexChanged(object sender, EventArgs e)
        {
            int state = int.Parse(ddlSelectState.SelectedValue);
            updateUIbyState(state);
            BindFlowInfo(ddlSelect, state);
            ddlSelect_SelectedIndexChanged(null, null);
        }

        private void updateUIbyState(int state)
        {
            if (state == 0 /*|| state == 3*/)
            {
                panelUpdateState.Visible = false;
            }
            else
            {
                panelUpdateState.Visible = true;
            }
        }

        private Info_workflowMaster getMasterState(int infoWKTypeID)
        {
            CustomsSystem.BLL.WorkflowManage bll = new WorkflowManage();
            CustomsSystem.Model.Info_workflowMaster master = bll.GetModelMaster(infoWKTypeID);
            if (master!=null)
            {
                return master;
            }
            return null;
        }

        private void adDLLStates()
        {
            ddlStates.Items.Clear();
            ddlStates.Items.Add(new ListItem("使用状态", "1"));
            ddlStates.Items.Add(new ListItem("禁用状态", "2"));
        }

        private void checkDDLCanUse(DropDownList ddl)
        {
            CustomsSystem.BLL.WorkflowManage bll = new CustomsSystem.BLL.WorkflowManage();
            CustomsSystem.Model.Info_workflowMaster model = bll.GetModelMaster(int.Parse(curWFTYPEID));
            if (model == null) return;
            if (model.States == 1)
            {
                btnDelete.Visible = false;
                isBeginUsed = true;
            }
            else
            {
                btnDelete.Visible = true;
                isBeginUsed = false;
            }
            //string str = isBeginUsed ?　"启用":"还没启用";
            //MessageBox.Show(this, "当前模板" + str);
        }
        /// <summary>
        /// 获取所有工作流模板
        /// </summary>
        /// <param name="ddl"></param>
        private void BindFlowInfo(DropDownList ddl)
        {
            WorkflowManage wfBll = new WorkflowManage();
            List<Info_workflowMaster> wfModels = wfBll.GetModelListMaster("");
            foreach (Info_workflowMaster aflow in wfModels)
            {
                ddl.Items.Add(new ListItem(aflow.WKTypeName, aflow.infoWKTypeID.ToString()));
            }
        }
        /// <summary>
        /// 获取指定状态工作流模板
        /// </summary>
        /// <param name="ddl"></param>
        private void BindFlowInfo(DropDownList ddl , int state)
        {
            ddl.Items.Clear();
            WorkflowManage wfBll = new WorkflowManage();
            List<Info_workflowMaster> wfModels = wfBll.GetModelListMaster("");
            foreach (Info_workflowMaster aflow in wfModels)
            {
                if(aflow.States == state || state==3)
                    ddl.Items.Add(new ListItem(aflow.WKTypeName, aflow.infoWKTypeID.ToString()));
            }
        }

        /// <summary>
        /// 绑定员工列表
        /// </summary>
        /// <param name="ddl"></param>
        private void BindJobNoData(DropDownList ddl)
        {
            JobManage jobBll = new JobManage();
            List<Info_job> jobModels = jobBll.GetModelList("");
            foreach (Info_job aJob in jobModels)
            {
                ddl.Items.Add(new ListItem(aJob.jobName, aJob.jobNo.ToString()));
            }
        }

        /// <summary>
        /// 获取制定代码类型绑定到控件上
        /// </summary>
        /// <param name="ddl"></param>
        private void BindCodeData(DropDownList ddl, string codeType)
        {
            CodeManage codeBll = new CodeManage();
            List<Info_code> codeModels = codeBll.GetModelList("codeType='" + codeType + "'");
            foreach (Info_code aCode in codeModels)
            {
                ddl.Items.Add(new ListItem(aCode.codeName, aCode.codeID.ToString()));
            }
        }

        //
        protected void gvWorkflowview_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //转换编号为名字
                //string empNo = e.Row.Cells[3].Text;
                //e.Row.Cells[3].Text = ChangeNo2Name(empNo);
                DropDownList ddlBusID = e.Row.Cells[2].FindControl("ddlBusID") as DropDownList;
                if (ddlBusID != null) BindCodeData(ddlBusID, "busType");
                
                DropDownList ddlJobNo = e.Row.Cells[3].FindControl("ddlJobNo") as DropDownList;
                if (ddlJobNo != null) BindJobNoData(ddlJobNo);

                DropDownList ddlState = e.Row.Cells[7].FindControl("ddlgvState") as DropDownList;

                string busID = dt.Rows[e.Row.RowIndex]["busType"].ToString();
                string jobNo = dt.Rows[e.Row.RowIndex]["jobNo"].ToString();
                string state = dt.Rows[e.Row.RowIndex]["States"].ToString();
                if(busID=="99")
                {
                    ddlBusID.Items.Add(new ListItem("完结","99"));
                }
                ddlBusID.SelectedIndex = ddlBusID.Items.IndexOf(ddlBusID.Items.FindByValue(busID));
                
                ddlJobNo.SelectedIndex = ddlJobNo.Items.IndexOf(ddlJobNo.Items.FindByValue(jobNo));
                
                if(state!="")
                {
                    ddlState.SelectedIndex = ddlState.Items.IndexOf(ddlState.Items.FindByValue(state));
                }
               
                if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit))
                {
                    TextBox tb;
                    tb = e.Row.Cells[0].Controls[0] as TextBox;
                    if (tb != null) tb.Enabled = false;
                    tb= e.Row.Cells[1].Controls[0] as TextBox;
                    if (tb!=null) tb.Enabled = false;
                    //判断是否已经启动
                    if (isBeginUsed)//已经启用
                    {
                        ddlBusID.Enabled = false;
                        ddlJobNo.Enabled = false;
                        ddlState.Enabled=false;
                        //删除和编辑不可用
                        Button btnEdit = e.Row.Cells[8].Controls[0] as Button;
                        if (btnEdit!=null)  btnEdit.Enabled = false;
                        LinkButton btdel = e.Row.Cells[9].Controls[0] as LinkButton;
                        if (btdel != null) btdel.Enabled = false;
                    }
                }
                else
                {
                    //删除确认=
                    LinkButton btdel = e.Row.Cells[9].Controls[0] as LinkButton;
                    btdel.Attributes.Add("onClick", "return confirm('确认删除该行？')");
                    
                    ddlBusID.Enabled = false;
                    ddlJobNo.Enabled = false;
                    ddlState.Enabled=false;
                    if (isBeginUsed)//已经启用
                    {
                        //删除和编辑不可用
                        Button btnEdit = e.Row.Cells[8].Controls[0] as Button;
                        if (btnEdit != null) btnEdit.Enabled = false;
                        if (btdel != null) btdel.Enabled = false;
                    }
                }
            }
            
        }

        /// <summary>
        /// 将岗位编号转换为姓名
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        protected string ChangeNo2Name(string no)
        {
            //CustomsSystem.Model.Users model = new Users();
            JobManage bll = new JobManage();
            DataSet ds = bll.GetMyList("jobNo='" + no + "'");
            string name = "";
            if (ds.Tables[0].Rows.Count>0)
                name = ds.Tables[0].Rows[0]["jobName"].ToString();
            return name;
        }

        /// <summary>
        /// 将姓名转换为岗位编号
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        protected string ChangeName2No(string jobName)
        {
            //CustomsSystem.Model.Users model = new Users();
            JobManage bll = new JobManage();
            DataSet ds = bll.GetMyList("jobName='" + jobName + "'");
            string name = "";
            if (ds.Tables[0].Rows.Count > 0)
                name = ds.Tables[0].Rows[0]["jobNo"].ToString();
            return name;
        }

        private bool checkRepeat(string masterName)
        {
            //判断是否已存在这个流程名、
            List<Info_workflowMaster> masterList = new List<Info_workflowMaster>();
            masterList = bll.GetModelListMaster("");
            foreach (Info_workflowMaster model in masterList)
            {
                if (model.WKTypeName ==masterName)
                {
                    MessageBox.Show(this, "已经存在重名的工作流名称，请修改");
                    return true;
                }
            }
            return false;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

            CustomsSystem.BLL.WorkflowManage bll = new WorkflowManage();
            //CustomsSystem.Model.Info_workflowMaster model = bll.GetModelMaster(int.Parse(curWFTYPEID));
            List<Info_workflow> models = bll.GetModelList(" infoWKTypeID=" + curWFTYPEID);
            foreach (Info_workflow m in models)
            {
                bll.Delete(m.infoWKID);
            }
            bll.DeleteMaster(int.Parse(curWFTYPEID));
            MessageBox.ShowAndRedirect(this, "删除完成", HttpContext.Current.Request.Url.PathAndQuery);
        }
        

        //编辑
        protected void gvWorkflowview_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvWorkflowview.EditIndex = e.NewEditIndex;
            gvBind();//绑定  
        }
        //更新
        protected void gvWorkflowview_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (((TextBox)gvWorkflowview.Rows[e.RowIndex].Cells[1].Controls[0]).Text == "99")
            {
                MessageBox.Show(this, "完结行不能编辑！");
                return;
            }//完结行不能删除

            string id = gvWorkflowview.DataKeys[e.RowIndex].Values[0].ToString(); 
            //更新数据库
            Info_workflow model = bll.GetModel(Convert.ToInt32(id));

            string busID = "", jobNo = "", state="0";
            DropDownList ddl = (DropDownList)gvWorkflowview.Rows[e.RowIndex].Cells[2].FindControl("ddlBusID");
            if(ddl!=null) busID = ddl.SelectedValue;
            ddl = (DropDownList)gvWorkflowview.Rows[e.RowIndex].Cells[2].FindControl("ddlJobNo");
            if (ddl != null) jobNo = ddl.SelectedValue;
            ddl = (DropDownList)gvWorkflowview.Rows[e.RowIndex].Cells[7].FindControl("ddlgvState");
            if (ddl != null) state = ddl.SelectedValue;

            

            TextBox tb;
            tb=gvWorkflowview.Rows[e.RowIndex].Cells[4].Controls[0] as TextBox;
            string dotime = tb.Text;//处理时间
            tb = gvWorkflowview.Rows[e.RowIndex].Cells[5].Controls[0] as TextBox;
            string yellowtime = tb.Text;//处理警告时限
            tb = gvWorkflowview.Rows[e.RowIndex].Cells[6].Controls[0] as TextBox;
            string remark =tb.Text;//说明

            if(dotime==""||!PageValidate.IsNumber(dotime))//处理时限格式验证
            {
                MessageBox.Show(this,"处理时限只能为数字！");
                return;
            }
            if (yellowtime == "" || (yellowtime.Substring(0,1)!="-"||!PageValidate.IsNumberSign(yellowtime)))//警告时限格式验证
            {
                MessageBox.Show(this, "预警时限应为负数数字！");
                return;
            }
            //数据录入
            model.busType = int.Parse(busID);
            model.jobNo = jobNo;
            model.States=int.Parse(state);
            model.doTimeLimit=int.Parse(dotime);
            model.yellowBefore=int.Parse(yellowtime);
            model.remark=remark;
            
            bll.Update(model);

            gvWorkflowview.EditIndex = -1;
            gvBind();//绑定数据  
        }

        protected void gvWorkflowview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvWorkflowview.EditIndex = -1;
            gvBind();//绑定  
        }

        //删除
        protected void gvWorkflowview_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            int id = Convert.ToInt32(gvWorkflowview.DataKeys[e.RowIndex].Values[0]);
            if(gvWorkflowview.Rows[e.RowIndex].Cells[1].Text=="99")
            {
                MessageBox.Show(this,"完结行不能删除！");
                return;
            }
            //更新数据库
            bll.Delete(id);
            dt.Rows.RemoveAt(e.RowIndex);
            reNameId(dt);
            gvBind();//绑定
        }
        
        private void reNameId(DataTable newDt)
        {
            Info_workflow model;
            for (int i = 1; i <= newDt.Rows.Count; i++)
            {
                int infoWKid = Convert.ToInt32(newDt.Rows[i-1][0].ToString());
                model = bll.GetModel(infoWKid);
                model.stepID = i;
                bll.Update(model);
            }
        }

        /// <summary>
        /// 复制模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCopy_Click(object sender, EventArgs e)
        {
            int selectValue = Convert.ToInt32(ddlSelect.SelectedValue);
            Info_workflowMaster modelMaster = bll.GetModelMaster(selectValue);
            modelMaster.WKTypeName += "副本";
            if (checkRepeat(modelMaster.WKTypeName))
            {
                MessageBox.Show(this,"已经存在同名的模板。");
                return;
            }
            modelMaster.States = 0;
            int newID = bll.AddMaster(modelMaster);
            List<Info_workflow> models = bll.GetModelList(" infoWKTypeID = " + selectValue);
            foreach(Info_workflow m in models)
            {
                m.infoWKTypeID = newID;
                bll.Add(m);
            }
            BindFlowInfo(ddlSelect, Convert.ToInt32(ddlSelectState.SelectedValue));
            MessageBox.Show(this, "复制完成");
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpateState_Click(object sender, EventArgs e)
        {
            CustomsSystem.BLL.WorkflowManage bll = new WorkflowManage();
            CustomsSystem.Model.Info_workflowMaster model = bll.GetModelMaster(int.Parse(curWFTYPEID));
            string mName = tbMasterName.Text.Trim();
            if (checkRepeat(tbMasterName.Text.Trim())) return;
            model.WKTypeName = mName;
            bll.UpdateMaster(model);
            MessageBox.ShowAndRedirect(this, "更新成功","./workflowSettingView.aspx");
        }

        protected void btnUpateState1_Click(object sender, EventArgs e)
        {
            string curState = ddlStates.SelectedValue;
            CustomsSystem.BLL.WorkflowManage bll = new WorkflowManage();
            CustomsSystem.Model.Info_workflowMaster model = bll.GetModelMaster(int.Parse(curWFTYPEID));
            model.States = int.Parse(curState);
            bll.UpdateMaster(model);
            MessageBox.ShowAndRedirect(this, "更新成功", "./workflowSettingView.aspx");
        }


    }
}